<template>
  <WorkflowVue
    ref="workflowRef"
    main-height="calc(100vh - 148px)"
    :isCanvasEdit="isCanvasEdit"
    :parentstation-name="stationLabel"
    :stationId="stationId"
    :modelId="modelId"
  >
    <template #station>
      <div class="station-view">
        <n-popselect
          v-model:value="stationName"
          :options="stationList"
          size="large"
          trigger="click"
          style="min-width: 138px"
          @update:value="GetStationConfigurationFun"
        >
          <template v-if="superUser < 2 && isCanvasEdit" #action>
            <n-button color="#2F9832" @click="addStation">
              <template #icon>
                <icons class="icon" name="jiahao" />
              </template>
              新增工作台
            </n-button></template
          >
          <n-button
            v-if="!stationName"
            ghost
            type="success"
            style="min-width: 138px"
          >
            <div class="text">选择工作站</div>
            <icons class="icon" name="adown" />
          </n-button>
          <n-button v-else ghost type="success" style="min-width: 138px">
            <div class="text">{{ stationLabel }}</div>
            <icons class="icon" name="adown" />
          </n-button>
        </n-popselect>
        <div
          v-if="superUser < 2 && isCanvasEdit"
          class="edit-icon-btn"
          @click="openDelDialog = true"
        >
          <icons class="edit-icon" name="editIcon" />
        </div>
        <div v-else class="edit-icon-btn"></div>
      </div>
    </template>
    <template #btn>
      <div class="class-view">
        <div v-if="mapInfo" class="name">模块名称: {{ mapInfo.modelName }}</div>
        <div v-if="mapInfo" class="name">
          模块应用: {{ mapInfo.applicationType }}
        </div>
        <div v-if="mapInfo" class="name">
          模块属性: {{ mapInfo.moduleType }}
        </div>
      </div>
      <div class="set-btn">
        <div
          v-if="isCanvasEdit"
          class="btn pre"
          size="small"
          @click="updateConfig(false)"
        >
          预览
        </div>
        <div
          v-if="superUser < 2 && !isCanvasEdit"
          class="btn"
          size="small"
          @click="updateConfig(true)"
        >
          编辑
        </div>
        <div
          v-if="superUser < 2 && isCanvasEdit"
          class="btn"
          size="small"
          @click="saveConfig"
        >
          保存
        </div>
      </div>
    </template>
  </WorkflowVue>
  <n-modal
    :mask-closable="false"
    class="edit-dialog"
    v-model:show="openDelDialog"
    :show-icon="false"
    preset="dialog"
    :on-close="closeWin"
    transform-origin="center"
    style="background: #60676c; color: #fff; width: 300px"
  >
    <template #header>
      <div class="title-font">请选择删除的工位名称</div>
    </template>
    <div class="notice-info">
      <div v-for="tag in stationList" :key="tag.id" class="tag">
        <div class="text">
          {{ tag.label }}
        </div>
        <div class="tag-icon" @click="handleClick(tag)">
          <icons class="icon" name="delete" />
        </div>
      </div>
    </div>
  </n-modal>
  <div v-if="produceInfo" class="produce-info">
    <div class="name">产品名称</div>
    <div class="name mb">{{ produceInfo.productName }}</div>
    <div class="name">当前产品SN码</div>
    <div class="name">{{ produceInfo.productSN }}</div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from "vue";
import { useDialog } from "naive-ui";
import { useRoute } from "vue-router";
import WorkflowVue from "../../packages/A2";

import {
  GetPageInitData,
  UpdateStationConfiguration,
  GetStationConfiguration,
  DeleteStationConfiguration,
  GetAllStationInfo,
  GetProduceInfo,
} from "@/server";
import { useAppStore } from "@/store/modules/user";
const route = useRoute();
const dialog = useDialog();
const modelId = computed(() => route.params.id);
const store = useAppStore();
const superUser = computed(() => store.superUser);
const workflowRef = ref();
const mapInfo = ref(null) as any;
const stationList = ref([]) as any; //站点名称
const stationName = ref("");
const openDelDialog = ref(false);
const stationId = ref(-1);
watch(
  () => modelId.value,
  () => {
    GetPageInitDataFun();
    GetAllStationInfoFun();
  }
);
// 关闭删除
const closeWin = () => {
  openDelDialog.value = false;
};
const handleClick = (tag: any) => {
  dialog.warning({
    title: "删除站点配置",
    content: `确定是否要删除【${tag.label}】,将一并删除所有配置，是否确认？`,
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      // message.success("确定");
      DeleteStationConfigurationFun(tag.id);
    },
    onNegativeClick: () => {
      // message.error("不确定");
    },
  });
};
const DeleteStationConfigurationFun = async (id: number) => {
  const res: any = await DeleteStationConfiguration({ id: id });
  if (res.result.isSuccess) {
    GetAllStationInfoFun();
    closeWin();
    workflowRef.value?.GetAllStationListFun();
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const addStation = () => {
  stationId.value = 0;
  stationName.value = "";
  initData("[]", []);
};
//获取初始化数据
const GetPageInitDataFun = async () => {
  const res: any = await GetPageInitData({ modelId: modelId.value });
  if (res.result.isSuccess) {
    mapInfo.value = res.result.result;
  } else {
    store.error(res.result.message); // 错误提示
  }
};

onMounted(() => {
  GetPageInitDataFun();
  GetAllStationInfoFun();
});
const isCanvasEdit = ref(false); //默认不是编辑模式
const updateConfig = (type: boolean) => {
  isCanvasEdit.value = type;
};
const stationLabel = computed(() => {
  const data = stationList.value.find((e: any) => e.id === stationName.value);
  return data ? data.label : "";
});
//获取所有站点配置
const GetAllStationInfoFun = async (type?: boolean) => {
  const res: any = await GetAllStationInfo({
    modelId: modelId.value,
  });
  if (res.result.isSuccess) {
    stationList.value = res.result.result.map((e: any) => {
      return { value: e.id, label: e.stationName, id: e.id };
    });
    if (type) {
      if (stationId.value === 0) {
        stationName.value = stationList.value[stationList.value.length - 1].id;
        GetStationConfigurationFun(
          stationList.value[stationList.value.length - 1].id
        );
      } else {
        GetStationConfigurationFun(stationId.value);
      }
    } else {
      const name = sessionStorage.getItem("stationName");
      let stationId = null;
      if (name) {
        const index = stationList.value.findIndex((e: any) => e.label === name);
        if (index > -1) {
          stationId = stationList.value[index].id;
        }
      }
      if (stationId) {
        stationName.value = stationId;
        GetStationConfigurationFun(stationId);
      } else if (stationList.value.length > 0) {
        stationName.value = stationList.value[0].id;
        GetStationConfigurationFun(stationList.value[0].id);
      }
    }
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const GetStationConfigurationFun = async (id: number) => {
  sessionStorage.removeItem("stationName");
  stationId.value = id;
  const res: any = await GetStationConfiguration({
    Id: id,
  });
  if (res.result.isSuccess) {
    initData(res.result.result.position, res.result.result.steps);
    GetProduceInfoFun(id);
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const produceInfo = ref(null) as any;
const GetProduceInfoFun = async (id: number) => {
  const res: any = await GetProduceInfo({
    modelId: modelId.value,
    stationId: id,
  });
  if (res.result.isSuccess) {
    produceInfo.value = res.result.result;
  } else {
    store.error(res.result.message); // 错误提示
  }
};

const saveConfig = async () => {
  const mapData = workflowRef.value?.getData();
  const roundList = mapData.filter((e: any) => e.displayName === "round");
  if (roundList.length === 0) {
    store.warning("请添加节点"); // 错误提示
    return false;
  }
  const textList = mapData.filter((e: any) => e.displayName === "text");

  const roundListFormatted = roundList.map((roundItem: any) => {
    // Find the corresponding textItem using targetComponentId
    const textItem = textList.find(
      (text: any) => text.id === roundItem.next[0]?.targetComponentId
    );

    // Recursive function to find all partsName
    const findPartsName = (item: any): string[] => {
      if (!item) {
        return [];
      }
      const partsName: string[] = [item.label];

      if (item.next && item.next.length > 0) {
        item.next.forEach((nextItem: any) => {
          const nextTextItem = textList.find(
            (text: any) => text.id === nextItem.targetComponentId
          );
          partsName.push(...findPartsName(nextTextItem));
        });
      }
      return partsName;
    };

    return {
      plcAddress: roundItem.plcAddress,
      remark: roundItem.remark,
      partsName: findPartsName(textItem),
    };
  });
  const params: any = {
    modelId: modelId.value,
    stationName: roundList[0].name,
    position: JSON.stringify(mapData),
    steps: roundListFormatted,
  };
  if (modelId.value) {
    params.id = stationId.value;
  }
  const res: any = await UpdateStationConfiguration(params);
  if (res.result.isSuccess) {
    store.success(res.result.message); // 错误提示
    GetAllStationInfoFun(true);
    updateConfig(false);
    workflowRef.value?.GetAllStationListFun();
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const initData = (arr: any, data: any) => {
  const list = JSON.parse(arr).map((e: any) => {
    const item = data.find(
      (m: any) => m.remark === e.remark && e.plcAddress === m.plcAddress
    );
    if (item) {
      e.stepId = item.id;
    }
    return e;
  });
  workflowRef.value?.setData(list);
};
</script>

<style lang="less" scoped>
.work-page {
  display: flex;
  .right-btn {
    min-width: 100px;
    background: red;
  }
}
.class-view {
  display: flex;
  align-items: center;
  .name {
    font-size: 18px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #1c262d;
    line-height: 25px;
    margin-right: 20px;
    min-width: 150px;
  }
}
.station-view {
  display: flex;
  align-items: center;
  .edit-icon-btn {
    padding: 10px;
    .edit-icon {
      width: 24px;
      height: 24px;
    }
    margin-right: 30px;
  }
  .text {
    min-width: 100px;
  }
  .icon {
    margin-left: 5px;
    min-width: 16px;
    min-height: 16px;
  }
}
// 开始结束按钮
.icon-circle {
  border-radius: 50%;
  border: none;

  &.start {
    background: radial-gradient(circle at 70px 70px, #00b289, #eee);
  }

  &.end {
    background: radial-gradient(circle at 70px 70px, #fe6752, #eee);
  }
}
.edit-dialog {
  .title-font {
    color: #ffffff;
  }
  .notice-info {
    padding: 40px 0;
    .tag {
      font-size: 16px;
      background-color: rgba(32, 128, 240, 0.1);
      color: #ffffff;
      border: 1px solid #2080f0;
      padding: 6px 10px;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      .tag-icon {
        cursor: pointer;
      }
    }
  }
}
.produce-info {
  position: fixed;
  bottom: 0;
  left: 0;
  min-width: 180px;
  height: 180px;
  background: #e3e3e3;
  backdrop-filter: blur(32px);
  padding: 20px;
  .name {
    text-align: left;
    font-size: 18px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #1c262d;
    line-height: 25px;
  }
  .mb {
    margin-bottom: 20px;
  }
}
</style>
